<template>
    <div class="hello" ref="poster">
        <!-- 截图 -->
        <x-dialog v-model="printscreenShow" class="dialog-demo" hide-on-blur>
            <div class="img-box">
                <img :src="printscreenUrl" style="max-width:100%">
            </div>
            <div @click="printscreenShow=false">
                <span class="vux-close"></span>
            </div>
        </x-dialog>
        <div class="box pr" style="page-break-after: always">
            <img src="../assets/img/poster_bgc.png" alt="" class="bgcImg">
            <div class="topBox dflex pat40 sr pp p5">
                <div class="bdouBox">
                    <img :src="usersInfo.avatar +'?'+new Date().getTime()" crossOrigin="anonymous" class="img1 dl">
                    <div class="nickName fz12 w ta">{{ usersInfo.memberName }}</div>
                </div>

                <div>
                    <div class="w fz">已赚呗币</div>
                    <div>
                        <img src="../assets/img/bb.png" alt="" class="bbi dl wh" style="margin-bottom: 5px;">
                        <div class="fz yy dl">￥ {{ usersInfo.earnings }}</div>
                    </div>
                </div>
                <div>
                    <div class="w fz">{{ usersInfo.winRate }}%</div>
                    <div class="yy fz">胜率</div>
                </div>
                <div>
                    <div class="w fz">猜对{{ usersInfo.accumulatedGuessWinning }}次</div>
                </div>
            </div>

            <div class="qrcode pp dlfex m0 w fz16 sr" @click="clickPoster()">
                <div class="dl">
                    <div class="mb20">点击识别二维码</div>
                    <div>参与每日竞拍一起赢奖金</div>
                </div>
                <div class="code gray">
                    <div id="qrcode"></div>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
import html2canvas from 'html2canvas';
import QRcode from 'qrcodejs2'
import {personRecord, getShare, geTaskAddList, memberLogin} from '../api/index.js'
import {getAllToken, setAllToken} from '@/utils/auth'
import {Toast} from 'vant';
import {createLogger} from 'vuex';
import {XDialog} from 'vux'

export default {
    components: {
        [Toast.name]: Toast,
        XDialog
    },
    data() {
        return {
            usersInfo: {
                earnings: '10',
                memberName: '奖呗',
                avatar: "https://cdn.92jiangbei.com/newjiangbei/img/newImg/member/img-touxiang.png",
            },
            userImg: {},
            qrcode: '',
            url: '',
            headerImage: '',
            printscreenShow: false,
            printscreenUrl: '',
            para: {}

        }
    },
    created() {
        this.Share() //截图的参数
        this.memberNo = this.$store.state.user.memberNo || getAllToken("memberNo")

    },
    mounted() {
        this.createQrcode()   //创建完二维码再去创建海报
        this.getAuth()  //分享截图

    },
    methods: {
        Share() {// 战绩参数
            let para = {
                "memberNo": this.$store.state.user.memberNo || getAllToken("memberNo")
            }
            // console.log(para)
            personRecord(para).then(res => { //分享api
                if (res.data.code == "000") {
                    this.usersInfo = res.data.content;
                    this.usersInfo.avatar = this.usersInfo.avatar ? this.usersInfo.avatar : 'https://cdn.92jiangbei.com/newjiangbei/img/newImg/member/img-touxiang.png'
                    // console.log(this.usersInfo)
                } else {
                    Toast(`${res.data.desc}`)
                }
            })

        },
        createQrcode() {// 二维码生成
            let memberNo = JSON.parse(sessionStorage.getItem("memberNo"))   //首页登录的时候存下来的
            console.log(memberNo)
            this.qrcode = new QRcode(document.getElementById("qrcode"), {
                text: `https://uatguess.92jiangbei.com/#/Home?para=${JSON.stringify(memberNo)}`,
                width: 128,
                height: 128,
                correctLevel: 2
            })
        },
        // 点击海报，生成图片/
        async clickPoster() {
            const opts = {
                useCORS: true
            }
            const canvas = await html2canvas(this.$refs.poster, opts)
            this.printscreenUrl = canvas.toDataURL('image/png'); //a标签通过 canvas 转base64
            this.printscreenShow = true
        },

        base64ImgtoFile(dataurl, filename = 'file') {
            let arr = dataurl.split(',')
            console.log(arr, 'arr')
            let mime = arr[0].match(/:(.*?);/)[1]
            let suffix = mime.split('/')[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
        },

        getAuth() { //分享微信标题
            let tit = '小呗逛集';
            let iconUrl = 'https://cdn.92jiangbei.com/newjiangbei/img/newImg/share.png';
            let linkUrl = location.href.split('#')[0];
            let fxUrl = "";
            fxUrl = encodeURIComponent(location.href.split('#')[0])
            // let fxUrl = fxUrl;
            var data = {//请求参数
                url: fxUrl,
                serviceName: 'WX.AUTH.JB'
            }
            getShare(data).then(res => {//分享的参数
                console.log("报错error========================================>", res)
                localStorage.setItem("jsapi_ticket", res.data);
                let appId = res.data.appId;
                let timestamp = res.data.timestamp;
                let nonceStr = res.data.nonceStr;
                let signature = res.data.signature;

                // eslint-disable-next-line no-undef
                wx.config({
                    debug: true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: appId,         // 必填，公众号的唯一标识，填自己的！
                    timestamp: timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
                    nonceStr: nonceStr,   // 必填，生成签名的随机串
                    signature: signature, // 必填，签名，见附录1
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'updateAppMessageShareData',
                        'updateTimelineShareData'
                    ]
                })
                // eslint-disable-next-line no-undef
                wx.ready(function () {
                    //分享到朋友圈
                    // eslint-disable-next-line no-undef
                    wx.onMenuShareAppMessage({
                        title: tit,   // 分享时的标题
                        link: linkUrl,     // 分享时的链接
                        imgUrl: iconUrl,    // 分享时的图标
                        desc: '小呗带您逛集市，买礼券，送好友，玩转城市生活，点击立享更多折扣。',
                        success: function () {
                            if (getAllToken("memberNo")) {
                                let para = {
                                    memberNo: getAllToken("memberNo"),
                                    taskNo: 'MDT00004'
                                };
                                geTaskAddList(para)
                                    .then(res => {
                                        console.log("2")
                                    })
                                    .catch(err => {
                                    });
                            }

                        },
                        cancel: function () {
                            console.log("取消分享");
                        }
                    });
                    //分享给朋友
                    // eslint-disable-next-line no-undef
                    wx.onMenuShareTimeline({
                        title: tit,
                        desc: '小呗带您逛集市，买礼券，送好友，玩转城市生活，点击立享更多折扣。',
                        link: linkUrl,
                        imgUrl: iconUrl,
                        success: function () {
                            // alert(JSON.stringify(linkUrl))
                            if (getAllToken("memberNo")) {
                                let para = {
                                    memberNo: getAllToken("memberNo"),
                                    taskNo: 'MDT00004'
                                };
                                // alert(JSON.stringify(memberNo))
                                geTaskAddList(para) //每分享一次 掉一次任务成功接口
                                    .then(res => {
                                    })
                                    .catch(err => {
                                    });
                            }

                        },
                        cancel: function () {
                            console.log("取消分享");
                        }
                    });
                })
            })
        },


    },

}
</script>

<style scoped lang="less">
html, body, #app {
    height: 100%;
    margin: 0;
    padding: 0;
}

::-webkit-scrollbar { //页面无滚动
    width: 0 !important;
}

::-webkit-scrollbar {
    width: 0 !important;
    height: 0;
}

.hello {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0px;
    background-image: linear-gradient(to right, #473d9d, #8455a7, #473d9d);
    overflow-y: scroll;

}

.box {
    overflow-x: hidden;
    max-width: 100%;

    .bgcImg {
        background-attachment: fixed;
        height: 100%;
    }

    .topBox {
        width: 95%;
        height: 100px;
        border-radius: 25px;

        .bdouBox {
            .nickName {
                width: 60px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;

            }

            .img1 {
                width: 63px;
                height: 63px;
                border-radius: 32px;
            }
        }

    }

    .qrcode {
        width: 95%;
        height: 174px;
        border-radius: 25px;
        position: absolute;
        left: 50%;
        top: 70%;
        transform: translateX(-50%);

        .code {
            border: 1px solid gray;

            #qrcode {
                width: 128px;
                height: 128px;
            }
        }
    }
}

@import '~vux/src/styles/close';

.dialog-demo {
    .weui-dialog {
        border-radius: 8px;
        padding-bottom: 8px;
    }

    .dialog-title {
        line-height: 30px;
        color: #666;
    }

    .img-box {
        height: 95%;
        overflow: hidden;
    }

    .vux-close {
        margin-top: 8px;
        margin-bottom: 8px;
    }
}
</style>
